package com.appspot.bambugame.server.data;

import java.util.Date;

import javax.persistence.Id;

import com.googlecode.objectify.annotation.Cached;

@Cached
public class GlobalGameConfig
{
    @Id public long ID;
    public String CONFIG_KEY;
    public String CONFIG_VALUE;
    
    protected GlobalGameConfig()
    {
        
    }
    
    protected GlobalGameConfig(String pConfigKey)
    {
        CONFIG_KEY = pConfigKey;
        ID = getConfigDatastoreKey(pConfigKey);
    }
    
    public static GlobalGameConfig withKey(String pConfigKey)
    {
        return new GlobalGameConfig( pConfigKey );
    }
    
    public GlobalGameConfig withValue(String pConfigValue)
    {
        CONFIG_VALUE = pConfigValue;
        return this;
    }
    
    public GlobalGameConfig withValue(long pConfigValue)
    {
        CONFIG_VALUE = Long.toString( pConfigValue );
        return this;
    }
    
    public static long getConfigDatastoreKey(String pConfigKey)
    {
        return pConfigKey.hashCode();
    }
    
    public GlobalGameConfig(String pConfigKey, String pConfigValue)
    {
        this(pConfigKey);
        CONFIG_VALUE = pConfigValue;
    }
    
    public GlobalGameConfig(String pConfigKey, long pConfigValue)
    {
        this(pConfigKey, Long.toString( pConfigValue ) );
    }
    
    public GlobalGameConfig(String pConfigKey, double pConfigValue)
    {
        this(pConfigKey, Double.toString( pConfigValue ) );
    }
    
    public GlobalGameConfig(String pConfigKey, Date pConfigValue)
    {
        this( pConfigKey, pConfigValue.getTime() );
    }
    
    public String getStringValue()
    {
        return CONFIG_VALUE;
    }
    
    public Double getDoubleValue()
    {
        if (getStringValue() == null) return null;
        
        try
        {
            return Double.parseDouble( getStringValue() );
        }
        catch (NumberFormatException ex)
        {
            return 0D;
        }
    }
    
    public Long getLongValue()
    {
        if (getStringValue() == null) return null;
        
        try
        {
            return Long.parseLong( getStringValue() );
        }
        catch (NumberFormatException ex)
        {
            return 0L;
        }
    }
    
    public Date getDateValue()
    {
        Long tDateLongValue = getLongValue();
        if (tDateLongValue == null) return null;
        return new Date(tDateLongValue);
    }
}
